package cn.wizzer.app.task.commons.ext.quartz.job;

import cn.wizzer.app.crown.modules.models.CrownConfig;
import cn.wizzer.app.crown.modules.services.CrownConfigService;
import cn.wizzer.app.crown.modules.services.pl.bk.BKFsResolverService;
import cn.wizzer.app.crown.modules.services.pl.ft.FsResolverService;
import cn.wizzer.framework.util.ThreadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * @author
 */
@IocBean
public class CrownJobMatchFs implements Job {
    @Inject
    @Reference(retries = 3, timeout = 500000)
    private FsResolverService ftFs;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private BKFsResolverService bkFs;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private CrownConfigService crownConfigService;

    private static final Log log = Logs.get();


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取一个爬虫账号 线程安全
        CrownConfig crownConfig = crownConfigService.syncOne("冠军爬取任务");
        if (null != crownConfig) {
            log.info("准备开始任务:" + crownConfig);
            ThreadUtil.execute(new Runnable() {
                @Override
                public void run() {
                    crawler(crownConfig, jobExecutionContext);
                }
            });
        }
    }

    private void crawler(CrownConfig crownConfig, JobExecutionContext jobExecutionContext) {
        try {
            // 足球冠军
            ftFs.crawler(crownConfig);
            // 篮球冠军
            bkFs.crawler(crownConfig);
        } catch (Exception e) {
            log.error("冠军定时任务异常" + e.getMessage());
        } finally {
            crownConfigService.release(crownConfig);
        }
    }

}
